package com.harvest.scientific.ladder.page.ui.main

import androidx.lifecycle.viewModelScope
import com.harvest.scientific.ladder.base.BaseMVIViewModel
import com.harvest.scientific.ladder.base.IUiIntent
import com.harvest.scientific.ladder.base.IUiState
import com.harvest.scientific.ladder.net.request
import com.harvest.scientific.ladder.util.LogUtils
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.launch
import org.json.JSONObject


sealed class LoadUiState : IUiState {
    object Idle : LoadUiState()  //默认空闲
    data class Loading(var isShow: Boolean) : LoadUiState()  //展示Loading
    object ShowContent : LoadUiState()           //展示布局
    data class GetAppSettings(val maxDay: String = "", val maxCredit: String = "", val isBanner: String =""): LoadUiState()

    data class QueryInjurePacificChicken(val datas:List<InjurePacificChickenRes>) : LoadUiState()
    data class DislikeRoughSpear(val data: DislikeRoughSpeRes) : LoadUiState()

    data class Error(val msg: String) : LoadUiState()  //失败
}

sealed class HomeIntent : IUiIntent {
    data class QueryAppSettings(val key: String) : HomeIntent()

    object QueryInjurePacificChicken: HomeIntent()
    object DislikeRoughSpear: HomeIntent()
}

class MainViewModel : BaseMVIViewModel<HomeIntent, LoadUiState>() {
    private val repository by lazy { MainRepository()}

    private val _dislikeRoughSpe by lazy { MutableSharedFlow<DislikeRoughSpeRes>(replay = 1) }
    val dislikeRoughSpe = _dislikeRoughSpe.asSharedFlow()


    override fun initUiState(): LoadUiState {
        return LoadUiState.Idle
    }

    override fun handleIntent(intent: HomeIntent) {
        LogUtils.d("handleIntent ${intent is HomeIntent.QueryAppSettings}")

        when (intent) {
            is HomeIntent.QueryAppSettings -> {

                queryAppSettings(intent.key)
            }

            is HomeIntent.QueryInjurePacificChicken -> {
                queryInjurePacificChicken()
            }

            is HomeIntent.DislikeRoughSpear -> {
                dislikeRoughSpear()
            }
        }
    }

    fun queryInjurePacificChicken(callback : ((List<InjurePacificChickenRes>) -> Unit)? = null) {

        request(requestBlock = {

            repository.queryInjurePacificChicken()

        }, callBack = {
            onSuccess = { ret ->

                ret?.let {

                    LogUtils.d("queryInjurePacificChicken, res -> $it")
                    if (callback != null) {
                        callback?.invoke(it)

                    } else {

                        if (it.size <= 1) {
                            dislikeRoughSpear()

                        } else {
                            updateUiState {
                                LoadUiState.QueryInjurePacificChicken(it)
                            }
                        }
                    }
                }

            }
            onFailed = { code, str ->
                LogUtils.d("queryAppSettings error, code:$code, errorStr:$str")
            }
        })
    }

    fun dislikeRoughSpear() {

        LogUtils.d("dislikeRoughSpear start")
        request(
            requestBlock = {
                repository.dislikeRoughSpear()
            },
            callBack = {
                onSuccess = {res->
                    LogUtils.d("DiskReadViolation, res request-> $res")
                    res?.let {
                        viewModelScope.launch {
                            _dislikeRoughSpe.emit(res)
                        }

                        updateUiState {
                            LoadUiState.DislikeRoughSpear(res)
                        }
                    }
                }

                onFailed = {code, codeStr ->

                    LogUtils.d("dislike error, $code, $codeStr")
                }
            }
        )
    }


    private fun queryAppSettings(key: String) {
        LogUtils.d("queryAppSettings, key:$key")
//        viewModelScope.launch {
//            val keyJob = async {
//                repository.queryAppSettings(key)
//            }
//
//            val prettyCrazyHerbJob = async {
//                repository.queryAppSettings("prettyCrazyHerb")
//            }
//            val cloudyMidAshamedLieNoseJob = async {
//                repository.queryAppSettings("cloudyMidAshamedLieNose")
//            }
//
//            val keyRet = keyJob.await()
//            val prettyCrazyHerbRet = prettyCrazyHerbJob.await()
//            val cloudyMidAshamedLieNoseRet = cloudyMidAshamedLieNoseJob.await()
//
//            LogUtils.d("keyRet = ${keyRet} ${keyRet.hashCode()}., prettyCrazy:$prettyCrazyHerbRet, prettyCrazyHerb:${cloudyMidAshamedLieNoseRet}")
//
//
//
//
//        }

        request(requestBlock = {

            repository.queryAppSettings(key)

        }, callBack = {
            onSuccess = { ret ->

                ret?.let {

                    val keyRet  = JSONObject(ret.toString()).optString(key)
                    updateUiState {
                        when (key) {

                            // max day
                            "tightBlueEyesight" -> {
                                LoadUiState.GetAppSettings(maxDay = keyRet)
                            }
                            // test max day
                            "unknownHatProbableScholar" -> {
                                LoadUiState.GetAppSettings(maxDay =  keyRet)
                            }

                            // max amount
                            "prettyCrazyHerb" -> {
                                LoadUiState.GetAppSettings(maxCredit = keyRet)
                            }

                            // test max amount
                            "deliciousLeafDevelopment" -> {
                                LoadUiState.GetAppSettings(maxCredit = keyRet)
                            }

                            "cloudyMidAshamedLieNose" -> {
                                LoadUiState.GetAppSettings(isBanner = keyRet)
                            }

                            else -> {
                                LoadUiState.GetAppSettings()
                            }
                        }
                    }
                }

            }
            onFailed = { code, str ->
                LogUtils.d("queryAppSettings error, code:$code, errorStr:$str")
            }
        })

    }

}